export class CustomPlayer {
    constructor(url: string, dom: HTMLElement) {
        this.url = url
        this.dom = dom
    }

    url: string
    dom: HTMLElement
    player: ZLMRTCClient.Endpoint | null = null

    play() {
        this.player = new ZLMRTCClient.Endpoint({
            element: this.dom,
            debug: true,
            zlmsdpUrl: this.url,
            simulecast: false,
            useCamera: false,
            audioEnable: false,
            videoEnable: false,
            recvOnly: true,
        })

        this.player.on(ZLMRTCClient.Events.WEBRTC_ICE_CANDIDATE_ERROR, () => {
            console.error('ICE 协商出错')
        });

        this.player.on(ZLMRTCClient.Events.WEBRTC_ON_REMOTE_STREAMS, (e) => {
            console.log('播放成功', e.streams)
        });

        this.player.on(ZLMRTCClient.Events.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED, (e) => {
            console.error('offer anwser 交换失败', e)
            if (e.code == -400 && e.msg == "流不存在") {
                setTimeout(() => {
                    if (this.player) {
                        this.player.close();
                    }
                    this.play()
                }, 100)

            }
        });

        this.player.on(window.ZLMRTCClient.Events.WEBRTC_ON_LOCAL_STREAM, () => {// 获取到了本地流
            console.info("LOCAL STREAM", "获取到了本地流")
        });
    }

    close() {
        this.player?.close();
    }
}